package com.irdstudio.efp.esb.api.rest.sed.ploaninfo;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.irdstudio.basic.framework.core.base.FrameworkService;
import com.irdstudio.basic.framework.core.constant.EsbRetCodeStandard;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.efp.esb.api.bean.sed.ploaninfo.ReqPersonalRepayDetail;
import com.irdstudio.efp.esb.api.bean.sed.ploaninfo.RespPersonalRepayDetail;
import com.irdstudio.efp.esb.api.common.EsbRespServiceBeanCreator;
import com.irdstudio.efp.esb.api.service.sed.SedCommonService;
import com.irdstudio.efp.esb.api.service.sed.ploaninfo.PersonalRepayDetailService;
import com.irdstudio.efp.esb.common.constant.EsbBizEnums;
import com.irdstudio.efp.esb.common.constant.EsbSysHeadEnums;
import com.irdstudio.efp.esb.common.constant.RespRetCode;
import com.irdstudio.efp.esb.common.server.req.EsbReqServiceBean;
import com.irdstudio.efp.esb.common.server.resp.EsbRespServiceBean;
import com.irdstudio.efp.esb.service.bo.req.hj.RepayInfoQueryReqBean;
import com.irdstudio.efp.esb.service.bo.resp.hj.RepayInfoQueryRespBean;
import com.irdstudio.efp.esb.service.facade.hj.RepayInfoQueryService;
import com.irdstudio.efp.loan.service.facade.AccLoanService;
import com.irdstudio.efp.loan.service.facade.LoanRepayDetailService;
import com.irdstudio.efp.loan.service.vo.AccLoanVO;
import com.irdstudio.efp.loan.service.vo.LoanRepayDetailVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.jsf.FacesContextUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
* 普税贷产品对税e贷产品的此部分代码做了复用
* 说明：为了保证功能的复用性、提升开发的工作效率，对该代码进行了复用
* 评估是否会影响线上功能：否
* 评估时间：2020/5/25
* 处理方案：保留复用
*/
/**
 * 需求编号：【2019D0519】
 * 问题编号：【】
 * 服务场景描述：个人还款明细查询 <br>
 * @author xiaojunhui
 * @version 0.1
 * @date 2019/5/20 17:13
 */
@RestController
@RequestMapping("/esb")
public class PersonalRepayDetailController implements FrameworkService {

	private static Logger logger = LoggerFactory.getLogger(PersonalRepayDetailController.class);

	@Autowired
	private SedCommonService<RespPersonalRepayDetail> sedCommonService;

	@Autowired
	private PersonalRepayDetailService personalrepayDetailService;

	@Autowired
	@Qualifier("loanRepayDetailService")
	private LoanRepayDetailService loanRepayDetailService;

	@Autowired
	private RepayInfoQueryService repayInfoQueryService;

	@Autowired
	private AccLoanService accLoanService;

	/**
	 * 获取ESB请求对象，校验 ESB请求系统头和请求应用头对象
	 *
	 * @param request 请求对象集合
	 * @return
	 */
	@ModelAttribute("esbReqServiceBean")
	public EsbReqServiceBean getReqEsbHeadBean(HttpServletRequest request) {
		logger.info("校验 ESB请求系统头和请求应用头对象!");
		EsbReqServiceBean esbReqServiceBean = (EsbReqServiceBean) request.getAttribute("esbReqServiceBean");
		return esbReqServiceBean;
	}

	/**
	 * 获取ESB请求对象，校验 ESB请求体对象
	 *
	 * @param request 请求对象集合
	 * @return
	 */
	@ModelAttribute("reqPersonalRepayDetail")
	public ReqPersonalRepayDetail getReqEsbBodyBean(HttpServletRequest request) {
		logger.info("校验 ESB请求体对象！");
		String esbReqBody = (String) request.getAttribute("esbReqBody");
		return JSONObject.parseObject(esbReqBody, ReqPersonalRepayDetail.class, Feature.InternFieldNames);
	}

	/**
	 * 处理请求
	 *
	 * @param esbReqServiceBean      esb请求对象
	 * @param br1
	 * @param reqPersonalRepayDetail 返回对象
	 * @param br2
	 * @param exception
	 * @return
	 */
	@PostMapping("/SERVICE_30230002_05")
	public EsbRespServiceBean doRecv(@Validated @ModelAttribute("esbReqServiceBean") EsbReqServiceBean esbReqServiceBean, BindingResult br1,
                                     @Validated @ModelAttribute("reqPersonalRepayDetail") ReqPersonalRepayDetail reqPersonalRepayDetail,
                                     BindingResult br2, Exception exception) {
		String glblSrlNo = esbReqServiceBean.getSysHead().getGlblSrlNo();
		logger.info("还款明细查询开始,全局流水号为：[{}]", glblSrlNo);
		//页码-当前查询第几页的数据
		String pageNo = reqPersonalRepayDetail.getPageNo();
		//每页显示条数
		String pageSize = reqPersonalRepayDetail.getPageSize();
		//响应体
		RespPersonalRepayDetail respPersonalRepayDetail = new RespPersonalRepayDetail();

		if (Objects.nonNull(exception)) {
			//如果异常不为空，那么处理异常返回信息
			return sedCommonService.getEsbRespServiceBeanByException(esbReqServiceBean, exception, respPersonalRepayDetail, RespRetCode.FAILE, EsbRetCodeStandard.JKYDCSJYBTG);
		}
		try {
			//根据查询类型封装不同条件的查询参数
			LoanRepayDetailVO transfer = personalrepayDetailService.transferQueryParams.transfer(reqPersonalRepayDetail);
			int[] offsetLimt = sedCommonService.getOffsetLimt(pageNo, pageSize);
			//查询总页数
			boolean singleQuery = StringUtils.isNotEmpty(reqPersonalRepayDetail.getSetlSeq()) ? true : false;
			int totalSize = singleQuery ? 1 : loanRepayDetailService.queryCountByBST(transfer);
			List<LoanRepayDetailVO> loanRepayDetailVOS = new ArrayList<LoanRepayDetailVO>();
			if (offsetLimt[0] <= totalSize) {
				loanRepayDetailVOS = loanRepayDetailService.queryLoanRepayDetailByBST(transfer, offsetLimt[0], offsetLimt[1]);
			}
			if (singleQuery && loanRepayDetailVOS.size() <= 0) {
				//直接输出
				return sedCommonService.getSucessBean(esbReqServiceBean, respPersonalRepayDetail, RespRetCode.SUCCESS);
			}
			//根据借据号查询
			AccLoanVO accLoanPkParam = new AccLoanVO();
			accLoanPkParam.setBillNo(StringUtils.isNotEmpty(reqPersonalRepayDetail.getBillNo()) ? reqPersonalRepayDetail.getBillNo() : loanRepayDetailVOS.get(0).getLoanNo());
			AccLoanVO accLoanVO = accLoanService.queryByPk(accLoanPkParam);
			if (Objects.isNull(accLoanVO)) {
				logger.info(reqPersonalRepayDetail.getBillNo(),"根据借据号获取到的借据数据为空");
				return sedCommonService.getEsbRespServiceBeanByException(esbReqServiceBean, new Exception("根据借据号获取到的借据数据为空"), respPersonalRepayDetail, RespRetCode.FAILE, EsbRetCodeStandard.SUCCESS);
			}
			//查询互金的还款记录查询
			RepayInfoQueryReqBean repayInfoQueryReqBean = new RepayInfoQueryReqBean();
			repayInfoQueryReqBean.setLoanNo(accLoanVO.getLoanSeq());
			repayInfoQueryReqBean.setDistrNo(accLoanVO.getDistrNo());
			if (singleQuery) {
				repayInfoQueryReqBean.setRpyNo(loanRepayDetailVOS.get(0).getRpyNo());
			}
			repayInfoQueryReqBean.setGlobaNo(glblSrlNo);
			RepayInfoQueryRespBean repayInfoQueryRespBean = repayInfoQueryService.applyRepayInfoQuery(repayInfoQueryReqBean);
			/*if (Objects.isNull(repayInfoQueryRespBean)) {
				return sedCommonService.getEsbRespServiceBeanByException(esbReqServiceBean, new Exception("还款记录信息查询失败，请稍后再试"), respPersonalRepayDetail, RespRetCode.FAILE, EsbRetCodeStandard.JKYDCSJYBTG);
			}*/
			//封装响应报文
			personalrepayDetailService.handleResp(singleQuery, respPersonalRepayDetail, loanRepayDetailVOS, accLoanVO, repayInfoQueryRespBean);
			respPersonalRepayDetail.setPageNo(offsetLimt[2] + "");
			respPersonalRepayDetail.setPagSize(offsetLimt[1] + "");
			respPersonalRepayDetail.setTotalSize(String.valueOf(respPersonalRepayDetail.getRepayDetailArr().size()));

			//返回报文
			return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
					JSONObject.toJSONString(respPersonalRepayDetail,  SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullListAsEmpty,SerializerFeature.WriteNullStringAsEmpty,SerializerFeature.WriteNullNumberAsZero,SerializerFeature.WriteMapNullValue),
					EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(),
					EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),
					"查询成功");
		} catch (BizException e) {
			logger.error("还款明细接口出现异常，异常信息为：", e.getMessage());
			e.printStackTrace();
			return sedCommonService.getEsbRespServiceBeanByException(esbReqServiceBean, e, respPersonalRepayDetail, RespRetCode.FAILE, EsbRetCodeStandard.JKYDCSJYBTG);
		} catch (Exception ex) {
			logger.error("还款明细接口出现异常，异常信息为：", ex.getMessage());
			ex.printStackTrace();
			return sedCommonService.getEsbRespServiceBeanByException(esbReqServiceBean, ex, respPersonalRepayDetail, RespRetCode.FAILE, EsbRetCodeStandard.SJCLYC);
		}
	}
}
